<template>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars" color="#fff" :isLeft="true">
      <template #title><text style="color: #fff">附加金额</text></template>
    </GlobalTopBar>
    <!-- 内容 -->
    <view class="page_content">
      <view class="fwbox">
        <view class="fw_center">
          <view class="form_item fpadd border_b flex">
            <view class="label">附加金额：</view>
            <input
              class="inps"
              v-model="fromDttas.balance_payment_amount"
              type="number"
              placeholder="请输入附加金额"
            />
          </view>
          <view class="t2">上传工件照片（最多上传5张）</view>

          <view>
            <view class="ulimgbox" v-if="imgList.length">
              <view
                class="lib"
                v-for="(item, index) in imgList"
                :key="index + 1"
              >
                <image :src="item" mode="aspectFill" />
                <view class="close2" @click="imgList.splice(index, 1)">
                  <image
                    class="close2_img"
                    :src="`${store.imgDomain}close2.png`"
                    mode="aspectFill"
                  />
                </view>
              </view>
            </view>

            <view class="addimg" @click="chooseImage" v-if="imgList.length < 5">
              <uni-icons
                class="flex_center"
                type="plusempty"
                size="30"
                color="#90beb7"
              ></uni-icons
            ></view>
          </view>

          <view class="form_item ac">
            <view class="label">备注：</view>
            <textarea
              class="textareain border"
              v-model="fromDttas.balance_payment_remark"
              type="text"
              placeholder="请输入备注"
            />
          </view>

          <view class="form_item ac">
            <view class="label">物料：</view>
            <view class="jbxx_title flex_jb"
              >{{ dtext }}物料
              <view
                class="flex marginl"
                @click="store.to(`/pages/master/inventory/addtkd?type=2`)"
              >
                <uni-icons type="plus" size="24" color="#fff"></uni-icons>
                添加物料
              </view></view
            >
            <view
              class="center_li"
              v-for="(item, index) in material_variant_json_list"
              :key="index + 1"
            >
              <view class="border_b li_tops flex_jb">
                物料编码：{{ item.material_variant_number }}
                <uni-icons
                  type="trash"
                  size="22"
                  @click="material_variant_json_list.splice(index, 1)"
                ></uni-icons
              ></view>
              <view class="title">{{ item.material_title }}</view>
              <view class="flex jb"
                ><text>规格型号：{{ item.material_variant_title }}</text
                ><text>×{{ item.count }}</text></view
              >
              <view class="flex jb"
                ><text>品牌：{{ item.material_brand }}</text
                ><text
                  >售价：<text class="textac"
                    >￥{{
                      item.material_variant_sales_price ||
                      item.sales_price ||
                      item.sample_price
                    }}</text
                  >
                </text></view
              >
            </view>
          </view>

          <view class="form_item fpadd flex" style="margin-top: 20rpx">
            <view class="label" style="margin-left: auto"
              >尾款总金额：
              <text class="textac"
                >￥{{ Allbalance_payment_amount }}</text
              ></view
            >
          </view>

          <!-- 提交 -->
          <view class="btnbox">
            <view class="qx" @click="isShow2 = false">取消</view>
            <view class="tj" @click="doSaveServiceOrderBeginByWorker"
              >提交</view
            >
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onBeforeMount, watch, reactive } from 'vue';
import { useCounterStore } from '@/store';
import { onLoad, onShow } from '@dcloudio/uni-app';
import request from '@/utils/request';
import { formatTimestamp } from '@/utils/validate';
import tabBar from '@/components/tabBar.vue';
import SearchInput from '@/components/SearchInput.vue';

const jdform = reactive({
  service_order_id: '',
  refuse_reason: '',
  refuse_desc: '',
  historyscore_reduce: '',
});
const imgList = ref([]);
const isBz = ref(false);
const searchResult = ref('');
const store = useCounterStore();
const indexs = ref(0);
const datas = ref({});
const fromDttas = reactive({
  service_order_pending_payment_balance_payment_transaction_record_id: '',
  service_order_id: '',
  balance_payment_amount: '',
  balance_payment_remark: '',
  balance_payment_img: '',
  material_variant_json: '',
});
const material_variant_json_list = ref([]);
// 上传图
const chooseImage = () => {
  uni.chooseImage({
    count: 5 - imgList.value.length,
    sourceType: ['album', 'camera'], // 可选择相册或相机（拍照）
    success: (res) => {
      res.tempFilePaths.forEach((tempFilePath) => {
        onChooseAvatar(tempFilePath); // 单独的单张上传函数
      });
    },
    fail: (err) => {
      console.log('选择图片失败', err);
    },
  });
};
// 选择头像回调
const onChooseAvatar = (tempFilePaths) => {
  uni.uploadFile({
    url: 'https://adm.jinjiangservice.com/index.php/wxapp/common/uploadCommonImage',
    method: 'POST',
    filePath: tempFilePaths.detail?.avatarUrl || tempFilePaths,
    formData: {
      file: tempFilePaths.detail?.avatarUrl || tempFilePaths,
    },
    header: {
      'Content-Type': 'multipart/form-data',
    },
    name: 'file',
    success(res) {
      imgList.value.push(JSON.parse(res.data).data.path);
    },
  });
};
// 提交尾款申请/修改
const doSaveServiceOrderBeginByWorker = async () => {
  if (
    !fromDttas.balance_payment_amount &&
    !material_variant_json_list.value.length
  ) {
    uni.showToast({
      title: '请输入附加金额或选择物料',
      icon: 'none',
      mask: true,
    });
    return;
  }
  if (!fromDttas.balance_payment_remark) {
    uni.showToast({
      title: '请输入备注',
      icon: 'none',
      mask: true,
    });
    return;
  }
  fromDttas.balance_payment_img = imgList.value.join(',');
  fromDttas.material_variant_json = JSON.stringify(
    material_variant_json_list.value.map((item) => ({
      material_variant_id: item.material_variant_id,
      count: item.count,
    })),
  );

  console.log(666, {
    ...fromDttas,
    balance_payment_amount: Allbalance_payment_amount.value,
  });
  await request(
    'worker/order/doSaveServiceOrderBalancePaymentByWorker',
    { ...fromDttas, balance_payment_amount: Allbalance_payment_amount.value },
    'post',
  );
  uni.navigateBack({
    delta: 1,
  });
};

const Allbalance_payment_amount = computed(() => {
  if (!material_variant_json_list.value.length)
    return +fromDttas.balance_payment_amount;
  const Allamount = material_variant_json_list.value.reduce(
    (a, b) => (
      (a +=
        (+b.material_variant_sales_price || +b.sales_price || +b.sample_price) *
        b.count),
      a
    ),
    0,
  );
  return Allamount + +fromDttas.balance_payment_amount;
});

onShow(() => {
  if (store.navigateBackData.id) {
    const iy = material_variant_json_list.value.findIndex(
      (i) =>
        i.id ===
        (store.navigateBackData.id ||
          store.navigateBackData.material_variant_id),
    );
    if (iy != -1) {
      material_variant_json_list.value[iy].count +=
        +store.navigateBackData.count;
      store.navigateBackData = {};
      return;
    }
    material_variant_json_list.value.push(store.navigateBackData);
    store.navigateBackData = {};
  }
});

const balanceData = ref({});
onLoad((option) => {
  balanceData.value = JSON.parse(JSON.stringify(store.balanceData));
  store.balanceData = {};
  fromDttas.service_order_id = balanceData.value.id;
  console.log(22, balanceData.value);

  if (
    balanceData.value
      .service_order_pending_payment_balance_payment_transaction_record?.id
  ) {
    fromDttas.balance_payment_amount =
      balanceData.value.service_order_pending_payment_balance_payment_transaction_record.balance_payment_amount;
    fromDttas.service_order_pending_payment_balance_payment_transaction_record_id =
      balanceData.value.service_order_pending_payment_balance_payment_transaction_record.id;
    fromDttas.balance_payment_remark =
      balanceData.value.service_order_pending_payment_balance_payment_transaction_record.balance_payment_remark;
    if (
      balanceData.value
        .service_order_pending_payment_balance_payment_transaction_record
        .balance_payment_img
    )
      imgList.value =
        balanceData.value.service_order_pending_payment_balance_payment_transaction_record.balance_payment_img.split(
          ',',
        );
  }

  if (balanceData.value.service_order_material_variants.length) {
    material_variant_json_list.value = [
      ...balanceData.value.service_order_material_variants,
    ];
    const Allamount = material_variant_json_list.value.reduce(
      (a, b) => (
        (a +=
          (+b.material_variant_sales_price ||
            +b.sales_price ||
            +b.sample_price) * b.count),
        a
      ),
      0,
    );
    fromDttas.balance_payment_amount =
      +balanceData.value
        .service_order_pending_payment_balance_payment_transaction_record
        .balance_payment_amount - Allamount;
  }
});
</script>

<style lang="scss" scoped>
.topbars {
  background: linear-gradient(to right, #2bc1ac, #10b3a2);
}

.page_content {
  box-sizing: border-box;
  padding: 20rpx;
  position: relative;
}
.fwbox {
  .fw_center {
    position: relative;
    box-sizing: border-box;
    padding: 30rpx;
    border-radius: 20rpx;
    background-color: #fff;
    .t1 {
      font-size: 30rpx;
      margin-bottom: 40rpx;
    }
    .t2 {
      margin: 10rpx 0;
    }
    .imgbox {
      .libox {
        width: 25%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .btnbox {
      margin-top: 20rpx;
      display: flex;
      justify-content: flex-end;
      view {
        line-height: 46rpx;
        border-radius: 23rpx;
        padding: 0 50rpx;
      }
      .qx {
        color: #14c7b6;
        border: 1rpx solid #14c7b6;
      }
      .tj {
        margin-left: 20rpx;
        color: #fff;
        background-color: #15c9b7;
        border: 1rpx solid #15c9b7;
      }
    }
  }
}
.textareain {
  margin-top: 10px;
  box-sizing: border-box;
  padding: 10px;
  width: 100%;
}

.ulimgbox {
  margin: 20rpx 0;
  display: flex;
  flex-wrap: wrap;

  .lib {
    width: 150rpx;
    margin-bottom: 20rpx;
    margin-right: 40rpx;
    display: flex;
    flex-direction: column;
    position: relative;
    .close2_img {
      position: absolute;
      top: -15rpx;
      right: -15rpx;
      width: 30rpx;
      height: 30rpx;
    }
    image {
      border-radius: 20rpx;
      width: 150rpx;
      height: 150rpx;
    }
  }
}
.addimg {
  position: relative;
  width: max-content;
  border-radius: 20rpx;
  border: 1rpx dashed #90beb7;
  color: #90beb7;
  font-size: 100rpx;
  padding: 50rpx;
}
.form_item {
  display: flex;
  justify-content: space-between;
  margin-top: 10rpx;
  &.ac {
    flex-direction: column;
  }
}
.inps {
  text-align: right;
}
.fpadd {
  box-sizing: border-box;
  padding-bottom: 10rpx;
}
.jbxx_title {
  position: relative;
  box-sizing: border-box;
  padding: 0 0 0 20rpx;
  font-size: 30rpx;
  &::after {
    content: ' ';
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    height: 40rpx;
    width: 10rpx;
    border-radius: 5rpx;
    background-color: #15caba;
  }
}
.marginl {
  width: max-content;

  background-color: #12c3b1;
  border-radius: 10rpx;
  box-sizing: border-box;
  padding: 10rpx 20rpx;
  color: #fff;
}
.center_li {
  margin-top: 20rpx;
  background-color: #fff;
  padding: 20rpx;
  border: 1rpx solid #7fd2cb;
  box-sizing: border-box;
  border-radius: 10rpx;
  .li_tops {
    box-sizing: border-box;
    padding: 0 0 20rpx 0;
    margin-bottom: 20rpx;
  }
  .title {
    font-size: 30rpx;
    font-weight: 600;
  }
  .jb {
    justify-content: space-between;
    margin-top: 10rpx;
  }
}
.textac {
  color: #fb0201;
  font-size: 30rpx;
}
</style>
